<template>
  <div>
    <el-dialog
      v-toggle-full
      class="base-dialog"
      :class="{ readonly: readOnly }"
      :custom-class="'panna-dialog_big'"
      :title="title"
      :append-to-body="true"
      :visible.sync="innerDialogFormVisible"
      :before-close="handleClose"
    >
      <p slot="title">{{ title }}</p>

      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item v-if="moduleEnableEntrust" title="委托信息" name="1">
          <EntrustMaggessFormData
            ref="EntrustMaggessFormData"
            :read-only.sync="readOnly"
            :entrust-id.sync="entrustId"
            :state.sync="state"
            @closeChioseEntrustOrder="closeChioseEntrustOrder"
          />
        </el-collapse-item>
        <el-collapse-item title="样品信息" name="2">
          <SysBusinessSampleFormData
            ref="SysBusinessSampleFormData"
            :state.sync="state"
            :sample-detection-id.sync="sampleDetectionId"
            :read-only.sync="readOnly"
            :entrust-id.sync="entrustId"
            :entrust-sample-detection.sync="entrustSampleDetection"
            :sample-number.sync="sampleNumber"
            :detection-item.sync="detectionItem"
            @detectionItemClose="detectionItemClose"
            @samplingWayCodeChange="samplingWayCodeChange"
            @changeCustom="changeCustom"
          />
        </el-collapse-item>
        <el-collapse-item title="送样信息" name="3">
          <SampleDeliveryInfoFormData
            ref="SampleDeliveryInfoFormData"
            :read-only="readOnly"
          />
        </el-collapse-item>
        <el-collapse-item title="检验信息" name="4">
          <EntrustInspectionInfoFormData
            ref="EntrustInspectionInfoFormData"
            :read-only="readOnly"
          />
        </el-collapse-item>
        <el-collapse-item title="样品登记信息" name="5">
          <SampleRegistrationFormData
            ref="SampleRegistrationFormData"
            :read-only="readOnly"
          />
        </el-collapse-item>
      </el-collapse>
      <span v-if="!readOnly" slot="footer" class="base-dialog-footer">
        <el-button
          type="primary"
          :disabled="!submitLoad"
          @click="onSubmit('formData')"
          >保 存</el-button
        >
        <el-button @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  create,
  GetSampleRegistrationMaggess,
  getSampleNumber,
} from "../../../api/SampleManage/SampleRegistration";
import { getEntrustOrderSampleDetectionBySampleDetectionId } from "../../../api/EntrustManage/EntrustSampleDetection";
import EntrustMaggessFormData from "./FormDataEntrustMessage.vue";
import SysBusinessSampleFormData from "./FormDataSysBusinessSample.vue";
import SampleDeliveryInfoFormData from "./FormDataSampleDeliveryInfo.vue";
import EntrustInspectionInfoFormData from "./FormDataEntrustInspectionInfo.vue";
import SampleRegistrationFormData from "./FormDataSampleRegistration.vue";
import {GetDetectionItemNoPageList} from "@/ModuleSysBusiness/api/DetectionItemManage/SysBusinessDetectionItem.js";

import _ from "lodash";
// import sysbusiness from "panna-module-sysbusiness";
export default {
  name: "SampleRegistrationDialog",
  components: {
    EntrustMaggessFormData,
    SysBusinessSampleFormData,
    SampleDeliveryInfoFormData,
    EntrustInspectionInfoFormData,
    SampleRegistrationFormData,
  },
  props: {
    // 复制样品要改成true
    state: {
      type: Boolean,
      default: false,
    },
    moduleEnableEntrust: {
      type: Boolean,
      default: false,
    },
    dialogFormVisible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: String,
      default: "",
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    // 样品检测id
    sampleDetectionId: {
      type: String,
      default: "",
    },
    // 样品登记id
    sampleRegistrationId: {
      type: String,
      default: "",
    },
    // 委托单id
    entrustId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      detectionItem: [],
      samplingWayCode: "1",
      title: "",
      activeNames: ["1", "2", "3", "4", "5"],
      sampleNumberState: false,
      sampleNumber: "",
      id: 0,
      submitLoad: true,
      submitReadOnly: false,
      innerDialogFormVisible: false,
      // 委托样品检测id,选择委托单使用
      entrustSampleDetectionId: 0,
      // 委托样品检测数据,选择委托单使用
      entrustSampleDetection: {},
      // 检测项目id集合
      detectionItemIdList: [],
      // 委托单id
      entrustOrderId: 0,
      // 样品类别id
      sampleCategoryIdList: [],
      isCustomSampleNum: false,
    };
  },
  created() {
    this.innerDialogFormVisible = this.dialogFormVisible;
    if (this.entrustId) {
      this.entrustOrderId = this.entrustId;
    }

    this.sampleRegistration(this.sampleRegistrationId);
    this.sampleDetection(this.sampleDetectionId);
    if (this.readOnly) {
      this.title = "查看样品登记信息";
    } else {
      if (this.state) {
        this.title = "复制样品";
      } else {
        this.title = "新增样品登记信息";
      }
    }
    if (this.dialogFormVisible) {
      this.init();
      this.sampleDetection();
    }
  },
  methods: {
    // 样品登记id
    sampleRegistration(val) {
      if (val) {
        GetSampleRegistrationMaggess({ id: val }).then((res) => {
          this.detectionItem = res.data.sysBusinessDetectionItemGetListNoPages;
          this.detectionItemIdList = res.data.detectionItemIdList;
          this.sampleCategoryIdList = res.data.sampleCategoryIdList;
          if (this.moduleEnableEntrust) {
            if (res.data.entrustOrder != null) {
              this.$refs.EntrustMaggessFormData.formDataEntrustMaggess =
                res.data.entrustOrder;
              this.entrustOrderId = res.data.entrustOrder.id;
            }
          }
          this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.customerName =
            res.data.sampleRegistration.unitName;
          this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.customerAddress =
            res.data.sampleRegistration.unitAddress;
          this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.phone =
            res.data.sampleRegistration.phone;
          this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.entrustPeople =
            res.data.sampleRegistration.entrustPeople;
          this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.email =
            res.data.sampleRegistration.email;

          this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo =
            res.data.sysBusinessSampleInfo;
          this.$refs.SampleDeliveryInfoFormData.formDataSampleDeliveryInfo =
            res.data.sampleDeliveryInfo;
          this.$refs.EntrustInspectionInfoFormData.formDataEntrustInspectionInfo =
            res.data.entrustInspectionInfo;
          this.$refs.SampleRegistrationFormData.formDataSampleRegistration =
            res.data.sampleRegistration;
          this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.detectionItemName =
            res.data.detectionItemName;
          this.$refs.SampleRegistrationFormData.formDataSampleRegistration.permissionUserName =
            res.data.permissionUserName;
          this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleNum =
            res.data.sysBusinessSampleInfo.sampleNum;
          if (this.state) {
            this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleNum =
              this.sampleNumber;
          }
          // 因为有依赖所以样品类别id赋值后重新获取编号
          this.getNumber();
        });
      }
    },
    // 样品检测
    sampleDetection(val) {
      // 样品检测id不等于空查询委托单信息,样品检测，检测项目信息
      if (val) {
        getEntrustOrderSampleDetectionBySampleDetectionId({ id: val }).then(
          (res) => {
            this.$refs.SampleDeliveryInfoFormData.formDataSampleDeliveryInfo.count =
              res.data.capacity;
            this.$refs.EntrustMaggessFormData.formDataEntrustMaggess = res.data;
            this.detectionItemIdList = res.data.detectionItemIdList;
            this.entrustSampleDetectionId = res.data.entrustSampleDetectionId;
            this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleName =
              res.data.sampleName;
            if (res.data.sampleNum !== null && res.data.sampleNum !== "") {
              this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleNum =
                res.data.sampleNum;
            }

            var arr = res.data.serviceName.split(",");
            for (let i = 0; i < arr.length; i++) {
              arr[i] = arr[i].trim();
            }

            this.$refs.EntrustInspectionInfoFormData.formDataEntrustInspectionInfo.serviceName =
              Array.from(new Set(arr)).join(",");
            this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.detectionItemName =
              res.data.detectionItemName;
            this.$refs.SampleDeliveryInfoFormData.formDataSampleDeliveryInfo.samplingAddress =
              res.data.samplingPosition;
            this.$refs.SampleDeliveryInfoFormData.formDataSampleDeliveryInfo.inspectedUnit =
              res.data.inspectedAddress;
            GetDetectionItemNoPageList({
                idList: this.detectionItemIdList,
              })
              .then((res) => {
                this.detectionItem = res.data;
              });
            this.getNumber();
          }
        );
      }
    },
    // 首次加载
    init() {},
    // 检验类别改变
    samplingWayCodeChange(val) {
      this.samplingWayCode = val;
      this.getNumber();
    },
    changeCustom(val) {
      this.sampleNumberState = !val;
      this.isCustomSampleNum = val;
      this.getNumber();
    },
    getNumber() {
      if (!this.readOnly && !this.isCustomSampleNum) {
        // 获取样品编号
        getSampleNumber({
          sampleDetectionId: this.sampleDetectionId
            ? this.sampleDetectionId
            : 0,
          sampleCategoryIdList: this.sampleCategoryIdList,
          samplingWayCode: this.samplingWayCode,
          state: false,
        })
          .then((res) => {
            this.sampleNumber = res.data;
            // formDataSysBusinessSampleInfo.sampleNum为空说明委托单没有手输编号
            if (
              this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo
                .sampleNum === "" ||
              this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo
                .sampleNum === null
            ) {
              this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleNum =
                res.data;
              this.sampleNumberState = true;
            } else {
              // 如果不等于空判断sampleNumberState是否为true,true为使用生成的编号
              if (this.sampleNumberState) {
                this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.sampleNum =
                  res.data;
              }
            }
          })
          .catch(() => {});
      }
    },

    // 关闭选择检测项目的弹框
    detectionItemClose(data, detectionData) {
      this.sampleCategoryIdList = [];
      for (let i = 0; i < detectionData.length; i++) {
        this.sampleCategoryIdList.push(
          detectionData[i].sysBusinessSampleCategoryId
        );
      }
      this.detectionItemIdList = data;
      if (
        detectionData[0].detectionMethod !== null &&
        detectionData[0].detectionMethod !== ""
      ) {
        var arr = detectionData[0].detectionMethod.split(",");
        for (let i = 0; i < arr.length; i++) {
          arr[i] = arr[i].trim();
        }
        // 执行标准去重
        this.$refs.EntrustInspectionInfoFormData.formDataEntrustInspectionInfo.serviceName =
          Array.from(new Set(arr)).join(",");
      }
      this.getNumber();
    },
    // 关闭选择委托单
    closeChioseEntrustOrder() {
      // 委托单id
      this.entrustOrderId = this.$refs.EntrustMaggessFormData.entrustOrderId;
      // 委托样品检测id
      // this.entrustSampleDetectionId =
      //   this.$refs.EntrustMaggessFormData.entrustSampleDetectionId;
      // 检测项目id集合
      // this.detectionItemIdList =
      //   this.$refs.EntrustMaggessFormData.detectionItemIdList;
      // 委托样品检测数据
      // this.entrustSampleDetection =
      //   this.$refs.EntrustMaggessFormData.entrustSampleDetection;
      // if (
      //   this.$refs.EntrustMaggessFormData.detectionItemIdList !== null &&
      //   this.$refs.EntrustMaggessFormData.detectionItemIdList.length !== 0
      // ) {
      //   sysbusiness.Api["DetectionItemManage/SysBusinessDetectionItem"]
      //     .GetDetectionProductStandard({
      //       idList: this.$refs.EntrustMaggessFormData.detectionItemIdList,
      //     })
      //     .then((res) => {
      //       var name = [];
      //       for (let i = 0; i < res.data.length; i++) {
      //         name.push(res.data[i].nationalStandardNum);
      //       }
      //       name = [...new Set(name)];
      //       this.$refs.EntrustInspectionInfoFormData.formDataEntrustInspectionInfo.serviceName =
      //         name.join(",");
      //     });
      // }
    },
    // 提交
    onSubmit: _.throttle(function() {
      if (this.submitLoad) {
        this.submitLoad = false;
        // 样品信息验证
        this.$refs.SysBusinessSampleFormData.$refs.formDataSysBusinessSampleInfo.validate(
          (valid1) => {
            if (valid1) {
              this.loading = true;
              var sampleRegistrationDto =
                this.$refs.SampleRegistrationFormData
                  .formDataSampleRegistration;
              var sysBusinessSampleInfoDto =
                this.$refs.SysBusinessSampleFormData
                  .formDataSysBusinessSampleInfo;
              var sampleDeliveryInfoDto =
                this.$refs.SampleDeliveryInfoFormData
                  .formDataSampleDeliveryInfo;
              sampleDeliveryInfoDto.samplingDate = String(
                sampleDeliveryInfoDto.samplingDate
              );
              var entrustInspectionInfoDto =
                this.$refs.EntrustInspectionInfoFormData
                  .formDataEntrustInspectionInfo;
              // 委托样品检测id
              var entrustSampleDetectionId = this.entrustSampleDetectionId;
              // 检测项目id集合
              var detectionItemIdList = this.detectionItemIdList;
              // 委托基础信息
              sampleRegistrationDto.unitName =
                this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.customerName;
              sampleRegistrationDto.unitAddress =
                this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.customerAddress;
              sampleRegistrationDto.phone =
                this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.phone;
              sampleRegistrationDto.entrustPeople =
                this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.entrustPeople;
              sampleRegistrationDto.email =
                this.$refs.EntrustMaggessFormData.formDataEntrustMaggess.email;

              var data = {
                state: this.state,
                sampleRegistrationDto: sampleRegistrationDto,
                sysBusinessSampleInfoDto: sysBusinessSampleInfoDto,
                sampleDeliveryInfoDto: sampleDeliveryInfoDto,
                entrustInspectionInfoDto: entrustInspectionInfoDto,
                entrustSampleDetectionId: entrustSampleDetectionId,
                detectionItemIdList: detectionItemIdList,
                entrustOrderId: this.entrustOrderId,
                changeState: this.sampleNumberState,
              };
              if (!this.editId) {
                this.addAPI(data);
              } else {
                this.editAPI(data);
              }
            } else {
              this.submitLoad = true;
            }
          }
        );
        return false;
      }
    }, 2000),
    // 新增
    addAPI(data) {
      create(data)
        .then((res) => {
          this.handleClose();
          this.submitLoad = true;
        })
        .catch(() => {
          this.sampleDeliveryInfoDto = false;
          this.submitLoad = true;
        });
    },
    // 关闭弹框
    handleClose() {
      this.closeDialog();
    },
    cancel() {
      this.innerDialogFormVisible = false;
      this.$emit("update:dialogFormVisible", false);
    },
    closeDialog() {
      // 清空表单
      if (this.moduleEnableEntrust) {
        this.$refs.EntrustMaggessFormData.$refs.formDataEntrustMaggess.resetFields();
        this.$refs.EntrustMaggessFormData.detectionItemIdList = [];
        this.$refs.EntrustMaggessFormData.entrustSampleDetectionId = 0;
        this.$refs.EntrustMaggessFormData.entrustSampleDetection = {};
      }

      this.$refs.SysBusinessSampleFormData.$refs.formDataSysBusinessSampleInfo.resetFields();
      this.$refs.SampleDeliveryInfoFormData.$refs.formDataSampleDeliveryInfo.resetFields();
      this.$refs.EntrustInspectionInfoFormData.$refs.formDataEntrustInspectionInfo.resetFields();
      this.$refs.SampleRegistrationFormData.$refs.formDataSampleRegistration.resetFields();
      this.$refs.SysBusinessSampleFormData.formDataSysBusinessSampleInfo.samplingWayCode =
        Number("1");
      this.$emit("update:sampleRegistrationId", "");
      this.$emit("close");
      this.cancel();
    },
    handleChange() {},
  },
};
</script>
<style scoped>
.el-collapse-item__header {
  height: 38px;
  line-height: 20px;
  padding: 4px;
  background-color: #f1f8ff;
}

.el-collapse-item__content {
  padding-top: 25px;
  padding-bottom: 12.5px;
}
</style>
